<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getSubmissionStatsApi, getScoreRankApi, getHotProblemsApi } from '@/api/problem/stats'
import { Message } from '@arco-design/web-vue'

const router = useRouter()
const userStore = useUserStore()

// 公告和最新动态数据
const announcements = ref([
  { id: 1, title: '系统更新通知：SakuraOJ v1.0正式上线', date: '2024-10-15' },
  { id: 2, title: '第一届SakuraOJ编程大赛即将开始', date: '2024-10-20' },
  { id: 3, title: '新增题目分类功能上线公告', date: '2024-10-25' }
])

// 热门题目数据 (修改：移除静态数据，将由API填充)
const fetchedHotProblems = ref<API.HotProblemVo[]>([]) // 新增：用于存储从API获取的原始热门题目数据
const isLoadingHotProblems = ref(false) // 新增：热门题目加载状态

// 排行榜数据 (修改：移除静态数据，将由API填充)
const topUsers = ref<API.UserRankVo[]>([]) // 新增：用于存储从API获取的排行榜数据
const isLoadingLeaderboard = ref(false) // 新增：排行榜加载状态

// 提交日历数据 - 现在由 API 填充
const submissionCalendarData = ref<API.DailySubmissionStat[]>([])
const isLoadingCalendar = ref(false) // 添加加载状态

// 获取用户 ID (如果用户已登录)
const userId = computed(() => userStore.userInfo?.id)

// --- 日期范围计算 (用于 Home.vue 的特定逻辑) ---
const getCalendarDateRange = () => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const dayOfWeek = today.getDay() // 0 = Sunday, 6 = Saturday

  // 大约回溯 17 周 (119 天)
  // Home.vue 的原始逻辑是显示 17*7 = 119 个格子
  // 计算起始日期，确保它落在周日
  const startDate = new Date(today)
  startDate.setDate(today.getDate() - (119 - 1 - (6 - dayOfWeek))) // 回溯天数，考虑本周剩余天数
  const startDayOfWeek = startDate.getDay()
  if (startDayOfWeek !== 0) {
    startDate.setDate(startDate.getDate() - startDayOfWeek)
  }

  // 结束日期是本周的周六
  const endDate = new Date(today)
  if (dayOfWeek !== 6) {
    endDate.setDate(today.getDate() + (6 - dayOfWeek))
  }

  return {
    startDate: startDate.toISOString().split('T')[0],
    endDate: endDate.toISOString().split('T')[0],
    startDateObj: startDate,
    endDateObj: endDate
  }
}

// --- 数据获取 ---
onMounted(async () => {
  // 检查用户是否登录
  if (userId.value) {
    isLoadingCalendar.value = true
    try {
      const { startDate, endDate } = getCalendarDateRange()
      // 调用 API，使用 startDate 和 endDate
      const response = await getSubmissionStatsApi({ startDate, endDate })
      if (response.code === 0 && response.data) {
        submissionCalendarData.value = response.data
      } else {
        console.error('Failed to load submission calendar data:', response.message)
      }
    } catch (error) {
      console.error('Failed to load submission calendar data:', error)
    } finally {
      isLoadingCalendar.value = false
    }
  }

  // 获取排行榜数据 (新增)
  isLoadingLeaderboard.value = true
  try {
    const res = await getScoreRankApi({ pageSize: 4 }) // 获取前4名
    if (res.code === 0 && res.data) {
      topUsers.value = res.data
    } else {
      console.error('Failed to load leaderboard data:', res.message)
      topUsers.value = [] // 出错时清空或设置为默认值
    }
  } catch (error) {
    console.error('Failed to load leaderboard data:', error)
    topUsers.value = [] // 出错时清空或设置为默认值
  } finally {
    isLoadingLeaderboard.value = false
  }

  // 获取热门题目数据 (新增)
  isLoadingHotProblems.value = true
  try {
    let hotProblemsResponse = await getHotProblemsApi({}) // 尝试获取7天内热门 (limit 5 默认)
    if (hotProblemsResponse.code === 0 && hotProblemsResponse.data && hotProblemsResponse.data.length > 0) {
      fetchedHotProblems.value = hotProblemsResponse.data
    } else {
      // 如果7天内没有，尝试获取30天内热门
      hotProblemsResponse = await getHotProblemsApi({ periodDays: 30 })
      if (hotProblemsResponse.code === 0 && hotProblemsResponse.data) {
        fetchedHotProblems.value = hotProblemsResponse.data
      } else {
        console.error('Failed to load hot problems:', hotProblemsResponse.message)
        fetchedHotProblems.value = [] // 出错或无数据时清空
      }
    }
  } catch (error) {
    console.error('Failed to load hot problems:', error)
    fetchedHotProblems.value = [] // 出错时清空
  } finally {
    isLoadingHotProblems.value = false
  }
})

// --- 辅助函数 ---
// 获取日历提交颜色
const getSubmissionColor = (count: number) => {
  if (count === 0) return '#ebedf0'
  if (count < 3) return 'var(--color-primary-light-2)'
  if (count < 6) return 'var(--color-primary-light-3)'
  if (count < 9) return 'var(--color-primary-light-4)'
  return 'rgb(var(--primary-6))'
}

// 判断是否为未来日期（今天之后的日期）
const isFutureDate = (dateString: string) => {
  if (!dateString) return false
  const date = new Date(dateString)
  date.setHours(0, 0, 0, 0)
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date > today
}

// 获取悬浮提示内容
const getTooltipContent = (day: { date: string; count: number }) => {
  if (!day || !day.date) return ''
  const date = new Date(day.date)
  date.setHours(0, 0, 0, 0)
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  if (date > today) {
    return '未来日期'
  }
  return `${day.date}: ${day.count} 次提交`
}

// 计算每周的日期数组 (核心修改)
const weeks = computed(() => {
  // 移除了条件判断，确保即使没有数据也显示日历
  const { startDateObj, endDateObj } = getCalendarDateRange()
  const result: { date: string; count: number }[][] = []
  
  // 使用 API 返回的 submitDate
  const dataMap = new Map(
    submissionCalendarData.value
      .filter((d: API.DailySubmissionStat) => d.submitDate !== undefined) // 过滤掉 submitDate 为 undefined 的项
      .map((d: API.DailySubmissionStat) => [
        d.submitDate!, // 使用非空断言，因为已经过滤
        d.count ?? 0
      ] as [string, number]) // 添加类型断言
  )
  const allDaysInRange: { date: string; count: number }[] = []

  let currentDay = new Date(startDateObj)

  while (currentDay <= endDateObj) {
    const dateStr = currentDay.toISOString().split('T')[0]
    allDaysInRange.push({
      date: dateStr,
      count: (dataMap.get(dateStr) as number) || 0 // 从 map 获取 count
    })
    currentDay.setDate(currentDay.getDate() + 1)
  }

  // 按 7 天分割成周
  for (let i = 0; i < allDaysInRange.length; i += 7) {
    result.push(allDaysInRange.slice(i, i + 7))
  }

  // 确保刚好是 17 周 (119 天) 的数据，如果 API 数据不足或日期计算稍有偏差
  while (result.length < 17) {
    const lastWeek = result[result.length - 1] || []
    const fillerWeek = Array(7)
      .fill(null)
      .map((_, i) => {
        const lastDate =
          lastWeek.length > 0 ? new Date(lastWeek[lastWeek.length - 1].date) : new Date(endDateObj)
        lastDate.setDate(lastDate.getDate() + i + 1)
        return { date: `filler-${lastDate.toISOString().split('T')[0]}`, count: 0 }
      })
    result.push(fillerWeek)
  }
  if (result.length > 17) {
    return result.slice(0, 17) // 只取前17周
  }

  return result
})

// 获取月份数组 (基于日期范围)
const calendarMonths = computed(() => {
  if (weeks.value.length === 0) return []

  const { startDateObj, endDateObj } = getCalendarDateRange()
  const months = []
  let currentDate = new Date(startDateObj)
  currentDate.setDate(1) // 从每月1号开始检查

  let count = 0 // 防止死循环
  while (currentDate <= endDateObj && count < 24) {
    // 检查这个月是否至少有一天在我们的日期范围内
    const monthEndCheck = new Date(currentDate)
    monthEndCheck.setMonth(currentDate.getMonth() + 1)
    monthEndCheck.setDate(0) // 这个月的最后一天

    if (currentDate <= endDateObj && monthEndCheck >= startDateObj) {
      months.push(`${currentDate.getMonth() + 1}月`)
    }
    currentDate.setMonth(currentDate.getMonth() + 1)
    count++
  }

  return months
})

// 计算活跃天数 (改为计算属性)
const activeDaysCount = computed(() => {
  return submissionCalendarData.value.filter((day: API.DailySubmissionStat) => (day.count ?? 0) > 0).length
})

// 跳转到题目页面
const goToProblem = (problemId: number) => {
  router.push(`/problem/${problemId}`)
}

// 跳转到题库页面
const goToProblemBank = () => {
  router.push('/problem')
}

// 获取难度对应的样式
const getDifficultyStyle = (difficulty: string) => {
  switch (difficulty) {
    case 'EASY':
      return { color: '#00b42a', text: '简单' }
    case 'MEDIUM':
      return { color: '#ff7d00', text: '中等' }
    case 'HARD':
      return { color: '#f53f3f', text: '困难' }
    default:
      return { color: '#86909c', text: '未知' }
  }
}

// 跳转到积分排行榜页面
const goToScoreRankAll = () => {
  // router.push('/score-rank')
  Message.info('暂未开放')
}

// 处理后的热门题目数据，用于展示 (新增)
const hotProblemsForDisplay = computed(() => {
  return fetchedHotProblems.value.map((problem: API.HotProblemVo) => {
    const tagsArray = problem.tags ? problem.tags.split(',').map((tag: string) => tag.trim()).filter((tag: string) => tag) : []
    let acceptanceRate = 'N/A'
    if (problem.submitNum && problem.submitNum > 0) {
      acceptanceRate = ((problem.acceptedNum / problem.submitNum) * 100).toFixed(0) + '%'
    } else if (problem.submitNum === 0) {
        acceptanceRate = '0%'
    }

    return {
      ...problem, // 保留原始字段，如 id, title, difficulty
      id: problem.id, // 确保 id 存在，HotProblemVo 中已有 id
      tags: tagsArray,
      acceptance: acceptanceRate
    }
  })
})
</script>

<template>
  <div class="home-page">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1>欢迎来到 Sakura OJ</h1>
        <p>在这里提升你的编程技能，挑战各种难度的算法题目</p>
        <div class="welcome-actions">
          <a-button type="primary" size="large" @click="goToProblemBank"> 开始刷题 </a-button>
          <a-button v-if="!userStore.userInfo" size="large" @click="router.push('/login')">
            立即登录
          </a-button>
        </div>
      </div>
      <div class="welcome-image">
        <img src="@/assets/images/programming.svg" alt="编程挑战" />
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧内容：热门题目和排行榜 -->
      <div class="left-content">
        <!-- 热门题目部分 -->
        <a-card class="section-card" title="热门题目" :bordered="false">
          <template #extra>
            <a-button type="text" @click="goToProblemBank">查看更多</a-button>
          </template>
          <a-list :data="hotProblemsForDisplay" :loading="isLoadingHotProblems">
            <template #item="{ item }">
              <a-list-item class="problem-item" @click="goToProblem(item.problemId)">
                <div class="problem-info">
                  <div class="problem-title">
                    <span class="problem-id">{{ item.problemId }}.</span>
                    {{ item.title }}
                  </div>
                  <div class="problem-details">
                    <a-tag :color="getDifficultyStyle(item.difficulty).color">
                      {{ getDifficultyStyle(item.difficulty).text }}
                    </a-tag>
                    <a-tag v-for="tag in item.tags" :key="tag" color="arcoblue" size="small">
                      {{ tag }}
                    </a-tag>
                    <span class="acceptance">通过率: {{ item.acceptance }}</span>
                  </div>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </a-card>

        <!-- 排行榜部分 -->
        <a-card class="section-card" title="排行榜 (Top 5)" :bordered="false">
          <template #extra>
            <a-button type="text" @click="goToScoreRankAll">完整榜单</a-button>
          </template>
          <a-table
            :columns="[
              { title: '排名', dataIndex: 'rank', width: 70, align: 'center' },
              { title: '用户名', dataIndex: 'username', ellipsis: true },
              { title: '通过数', dataIndex: 'submitCount', width: 100, align: 'center' },
              { title: '积分', dataIndex: 'score', width: 100, align: 'center' }
            ]"
            :data="topUsers"
            :pagination="false"
            :loading="isLoadingLeaderboard" 
          />
        </a-card>
      </div>

      <!-- 右侧内容：系统公告和提交日历 -->
      <div class="right-content">
        <!-- 提交记录日历 -->
        <a-card class="section-card" :bordered="false" v-if="userStore.userInfo">
          <template #title>
            <div class="submission-title">
              <icon-calendar size="22" />
              <span>提交打卡记录</span>
              <span class="submission-stats">
                <span class="submission-total">{{ activeDaysCount }}</span> 天
                <a-tooltip content="最近活动时段内的提交天数">
                  <icon-info-circle size="14" />
                </a-tooltip>
              </span>
            </div>
          </template>
          <a-spin :loading="isLoadingCalendar" tip="加载日历中..." style="width: 100%">
            <div class="calendar-container">
              <div class="calendar-grid">
                <div
                  v-for="(week, weekIndex) in weeks"
                  :key="`week-${weekIndex}`"
                  class="calendar-week"
                >
                  <a-tooltip
                    v-for="(day, dayIndex) in week"
                    :key="day ? day.date : `placeholder-${weekIndex}-${dayIndex}`"
                    :content="getTooltipContent(day)"
                    mini
                    position="top"
                  >
                    <div
                      class="calendar-day"
                      :class="{ 'calendar-day-future': day && isFutureDate(day.date) }"
                      :style="{ backgroundColor: day ? getSubmissionColor(day.count) : '#ebedf0' }"
                    ></div>
                  </a-tooltip>
                </div>
              </div>
              <div class="calendar-months">
                <div v-for="(month, index) in calendarMonths" :key="index" class="month-label">
                  {{ month }}
                </div>
              </div>
              <div class="calendar-legend">
                <span class="legend-label">少</span>
                <div class="legend-boxes">
                  <div class="legend-box" style="background-color: #ebedf0"></div>
                  <div
                    class="legend-box"
                    style="background-color: var(--color-primary-light-2)"
                  ></div>
                  <div
                    class="legend-box"
                    style="background-color: var(--color-primary-light-3)"
                  ></div>
                  <div
                    class="legend-box"
                    style="background-color: var(--color-primary-light-4)"
                  ></div>
                  <div class="legend-box" style="background-color: rgb(var(--primary-6))"></div>
                </div>
                <span class="legend-label">多</span>
              </div>
            </div>
          </a-spin>
        </a-card>

        <!-- 系统公告部分 -->
        <a-card class="section-card" title="系统公告" :bordered="false">
          <a-list :data="announcements">
            <template #item="{ item }">
              <a-list-item class="announcement-item">
                <div class="announcement-content">
                  <a-typography-paragraph ellipsis>
                    {{ item.title }}
                  </a-typography-paragraph>
                </div>
                <div class="announcement-date">{{ item.date }}</div>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home-page {
  padding: 0 0 24px 0;
}

.welcome-section {
  display: flex;
  align-items: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, rgba(255, 192, 203, 0.2) 0%, rgba(255, 255, 255, 0.8) 100%);
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.welcome-content {
  flex: 1;
}

.welcome-content h1 {
  font-size: 2.5rem;
  margin-bottom: 16px;
  background: linear-gradient(45deg, #ff69b4, #1e90ff);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  display: inline-block;
}

.welcome-content p {
  font-size: 1.2rem;
  margin-bottom: 24px;
  color: var(--color-text-2);
  max-width: 600px;
}

.welcome-actions {
  display: flex;
  gap: 16px;
}

.welcome-image {
  flex: 1;
  max-width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.welcome-image img {
  max-width: 100%;
  max-height: 300px;
}

.main-content {
  display: flex;
  gap: 24px;
}

.left-content {
  flex: 3;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.section-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
}

.section-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.problem-item {
  cursor: pointer;
  transition: background-color 0.2s;
  padding: 8px 12px;
  border-radius: 4px;
}

.problem-item:hover {
  background-color: var(--color-fill-2);
}

.problem-info {
  width: 100%;
}

.problem-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.problem-id {
  color: var(--color-text-3);
  margin-right: 8px;
}

.problem-details {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.acceptance {
  color: var(--color-text-3);
  font-size: 12px;
}

.announcement-item {
  padding: 12px 0;
}

.announcement-content {
  flex: 1;
}

.announcement-date {
  color: var(--color-text-3);
  font-size: 12px;
}

/* 提交日历样式 */
.submission-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.submission-stats {
  margin-left: auto;
  font-size: 14px;
  color: var(--color-text-2);
  display: flex;
  align-items: center;
  gap: 4px;
}

.submission-total {
  font-weight: bold;
  color: #30a14e;
  font-size: 16px;
}

.calendar-container {
  padding: 16px 0;
  overflow: hidden;
}

.calendar-grid {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  overflow: visible;
}

.calendar-week {
  display: flex;
  flex-direction: column;
  margin-right: 3px;
}

.calendar-day {
  width: 14px;
  height: 14px;
  border-radius: 2px;
  margin: 2px 0;
}

.calendar-months {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  padding: 0 20px;
}

.month-label {
  font-size: 12px;
  color: var(--color-text-3);
}

.calendar-legend {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 16px;
  gap: 4px;
}

.legend-label {
  font-size: 12px;
  color: var(--color-text-3);
}

.legend-boxes {
  display: flex;
  gap: 2px;
}

.legend-box {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

/* 响应式调整 */
@media (max-width: 991px) {
  .main-content {
    flex-direction: column;
  }

  .welcome-section {
    flex-direction: column;
    text-align: center;
    padding: 24px 16px;
  }

  .welcome-content h1 {
    font-size: 2rem;
  }

  .welcome-content p {
    font-size: 1rem;
    margin: 0 auto 20px;
  }

  .welcome-actions {
    justify-content: center;
  }

  .welcome-image {
    max-width: 100%;
    margin-top: 24px;
  }

  .calendar-grid {
    overflow-x: auto;
  }

  .calendar-container {
    overflow-x: auto;
  }
}

@media (min-width: 992px) and (max-width: 1199px) {
  .welcome-content h1 {
    font-size: 2.2rem;
  }

  .welcome-image img {
    max-height: 250px;
  }
}

@media (min-width: 1200px) {
  .home-page {
    padding: 0 0 32px 0;
  }

  .welcome-section {
    padding: 48px 32px;
  }
}

.calendar-day-future {
  opacity: 0.3;
  background-color: var(--color-fill-2) !important;
}

/* 可以为 Spin 添加一些样式 */
:deep(.arco-spin) {
  min-height: 100px; /* 防止加载时塌陷 */
  display: block;
}
</style>
